// pages/templates/thiscanvas/thiscanvas.js
import authorize from '../../../utils/authorize';
import config from '../../../config/base.js';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    list: String,
    datas: Object,
    share:Boolean,
    segsid:String,
    bslnid:String,
    order:String,
    fshow:String
  },

  /**
   * 组件的初始数据
   */
  data: {
    imagePath: '', //生成图片的路径
    zhuli: false, //隐藏助力分享图片
  },
  ready() {
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //生成朋友圈图片
    createQuan() {
      var _this = this;
      var context = wx.createCanvasContext('mycanvas', 'this');
      if (this.properties.list==1){
        wx.showLoading({
          title: '图片生成中',
        })
        this.setWxbg(context)
      } else if (this.properties.list == 2){
        wx.showLoading({
          title: '图片生成中',
        })
        this.setJbg(context)
      }
      
    },
    //切圆方法
    circleImg(ctx, img, x, y, r) {
      ctx.save();
      var d = 2 * r;
      var cx = x + r;
      var cy = y + r;
      ctx.arc(cx, cy, r, 0, 2 * Math.PI);
      ctx.clip();
      ctx.drawImage(img, x, y, d, d);
      ctx.restore();
    },
    //接龙商品开始
    setJbg(context){
      let _this=this;
      let path = 'https://kpxd.zhengdianhaohuo.com/kpxd_mp/asset/free/god.png';
      wx.downloadFile({
        url: path,
        success(res) {
          context.drawImage(res.tempFilePath, 0, 0, 530, 810);
          _this.setJgoods(context);
        },
        fail(res) {
          wx.showToast({
            title: '绘制背景失败',
            icon: 'none'
          })
          wx.hideLoading()
          _this.setJgoods(context);
        }
      })
    },
    //绘制接龙商品图片
    setJgoods(context){
      let _this = this;
      console.log(_this.properties.datas.goodsPic[0])
      let pic = 'https:' + _this.properties.datas.goodsPic[0].url + '?x-oss-process=image/resize,m_lfit,h_500,w_500';
      wx.downloadFile({
        url: pic,
        success(res) {
          context.drawImage(res.tempFilePath, 20, 73, 490, 490);
          _this.setjtitle(context);
        },
        fail(res) {
          wx.hideLoading()
          wx.showToast({
            title: '绘制商品图片失败',
            icon: 'none'
          })
          _this.setjtitle(context);
        }
      })
    },
    //绘制接龙商品的名字
    setjtitle(context){
      let _this=this;
      let text = _this.properties.datas.goods.name;
      var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
      var temp = "";
      var row = [];
      context.setFontSize(26)
      context.setFillStyle("#333")
      for (var a = 0; a < chr.length; a++) {
        if (context.measureText(temp).width < 284) {
          temp += chr[a];
        } else {
          a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = "";
        }
      }
      row.push(temp);
      if (row.length > 2) {
        var rowCut = row.slice(0, 2);
        var rowPart = rowCut[1];
        var test = "";
        var empty = [];
        for (var a = 0; a < rowPart.length; a++) {
          if (context.measureText(test).width < 284) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        var group = empty[0] + "..." //这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (var b = 0; b < row.length; b++) {
        context.fillText(row[b], 20, 600 + b * 37, 284);
      }
      _this.setJprice(context);
    },
    //绘制初始价格
    setJprice(context){
      let price = '初始价：'+this.properties.datas.grad[0].goods_grads_price;
      context.setFontSize(24);
      context.setFillStyle("#333");
      context.fillText(price, 20, 690);
      this.bigJfont(context)
    },
    //最低价
    bigJfont(context){
      let low = this.properties.datas.grad.pop().goods_grads_price;
      context.setFontSize(40);
      context.setFillStyle("#FE3F3E");
      context.fillText(low, 198, 784);
      this.setJcode(context)
    },
    //绘制接龙商品的二维码
    setJcode(context){
      let _this = this;
      let datas = this.properties.datas;
      let token = wx.getStorageSync('auth_token');
      let store_id = '';
      let user_id = wx.getStorageSync('user_info').id;
      if (this.properties.order==1){
        store_id = this.properties.bslnid
      }else{
        store_id = wx.getStorageSync('user_info').lastView.seid
      }
      let segsid = this.properties.segsid;
 
      let paths = encodeURIComponent('pages/detail/dragon?segsid=' + segsid + '&store_id=' + store_id + '&share_id=' + store_id + '&sharerecode=detailcode&user_id=' + user_id);

      var url = config.apiUrl+'/getCustomerQrCode?' + '&path=' + paths + '&scene=1012' + '&auth_token=' + token;

      console.log(url)
      wx.downloadFile({
        url: url,
        success(res) {
          context.drawImage(res.tempFilePath, 343, 587, 160, 160);
          _this.setJhead(context)
        }, fail(res) {
          wx.hideLoading()
          wx.showToast({
            title: '绘制二维码失败',
            icon: 'none'
          })
          _this.setJhead(context)
        }
      })  
    },
    // 绘制当前接龙人的头像
    setJhead(context){
      let _this=this;
      let path = wx.getStorageSync('user_info').avatar;
      wx.downloadFile({
        url:path,
        success(res){
          _this.circleImg(context, res.tempFilePath, 387, 631, 36, 36);
          _this.look(context)
        },fail(res){
          wx.hideLoading();
          wx.showToast({
            title:'绘制头像失败',
            icon:'none'
          })
          _this.look(context)
        }
      })
    },


    //=========免费拿画背景================
    setWxbg(context) {
      let _this = this;
      let path = 'https://kpxd.zhengdianhaohuo.com/kpxd_mp/asset/free/can.png';
      wx.downloadFile({
        url: path,
        success(res) {
          context.drawImage(res.tempFilePath, 0, 0, 530, 810);
          _this.Head(context);
        },
        fail(res) {
          wx.showToast({
            title: '绘制背景失败',
            icon: 'none'
          })
          wx.hideLoading()
          _this.Head(context);
        }
      })
    },
    //头像
    Head(context) {
      let _this=this;
      let myHead = this.properties.datas.self_avatar;
      wx.downloadFile({
        url: myHead,
        success(res){
          console.log(res)
          _this.circleImg(context, res.tempFilePath, 20, 7, 30, 30);
          _this.userName(context)
        },fail(res){
          wx.hideLoading()
          wx.showToast({
            title:'绘制头像失败',
            icon:'none'
          })
          _this.userName(context)
        }
      })
    },
    //某个人正在免费拿
    userName(context) {
      let logoname = this.properties.datas.user_nickname;
      logoname = logoname.length > 6 ? logoname.slice(0, 6) + '...  正在砍价' : logoname + '  正在砍价';
      context.setFontSize(26);
      context.setFillStyle("#333");
      context.fillText(logoname, 100, 52);
      context.save();
      this.goods(context);
    },
    //商品图片
    goods(context) {
      let _this = this;
      let pic = 'https:' + _this.properties.datas.goods_pic + '?x-oss-process=image/resize,m_lfit,h_500,w_500';
      wx.downloadFile({
        url: pic,
        success(res) {
          context.drawImage(res.tempFilePath, 20, 73, 490, 490);
           _this.zero(context)
        },
        fail(res) {
          wx.hideLoading()
          wx.showToast({
            title: '绘制商品图片失败',
            icon: 'none'
          })
          _this.zero(context)
        }
      })
    },
    //0元拿
    zero(context) {
      let _this = this;
      let path = 'https://kpxd.zhengdianhaohuo.com/kpxd_mp/asset/bargain/one_money.png';
      wx.downloadFile({
        url: path,
        success(res) {
          context.drawImage(res.tempFilePath, 380, 93, 130, 59);
          _this.goodsTitle(context);
        },
        fail(res) {
          wx.hideLoading()
          wx.showToast({
            title: '绘制1分拿失败',
            icon: 'none'
          })
          _this.goodsTitle(context);
        }
      })
    },
    //商品名称
    goodsTitle(context) {
      let _this = this;
      let first = '';
      let secend = '';
      let name = _this.properties.datas.goods_title;
      if (name.length < 10) {
        first = name.slice(0, 10)
      } else if (name.length > 9 && name.length < 19) {
        first = name.slice(0, 10);
        secend = name.slice(10, 19)
      } else if (name.length > 19) {
        first = name.slice(0, 10);
        secend = name.slice(10, 19) + '...'
      }
      context.setFontSize(26);
      context.setFillStyle("#333");
      context.fillText(first, 86, 610);
      context.fillText(secend, 21, 646);
      context.save();
      this.price(context)
    },
    //市场价
    price(context) {
      let price = '市场价：' + this.properties.datas.goods_list_money;
      context.setFontSize(24);
      context.setFillStyle("#333");
      context.fillText(price, 20, 690);
      this.code(context)
    },
    //绘制二维码
    code(context) {
      let _this = this;
      let datas = this.properties.datas;
      let token = wx.getStorageSync('auth_token');
      let store_id = wx.getStorageSync('user_info').lastView.seid;
      let user_id = wx.getStorageSync('user_info').id;
  
      let path =encodeURIComponent('/pages/cutprice/bargaindetail?bnorid=' + datas.bnorid + '&sharerecode=cutPricecode&store_id=' +store_id + '&user_id=' + user_id)
      var url = config.apiUrl+'/getCustomerQrCode?' + '&path=' + path + '&scene=1012' + '&auth_token=' + token;
      console.log(url)
      wx.downloadFile({
        url: url,
        success(res) {
          context.drawImage(res.tempFilePath, 343, 587, 160, 160);
          _this.look(context)
        }, fail(res) {
          wx.hideLoading()
          wx.showToast({
            title: '绘制二维码失败',
            icon:'none'
          })
          _this.look(context)
        }
      })  
    },
    //=================免费拿结束========================
    //成品
    look(context) {
      let _this = this;
      context.draw(false, function (e) {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: function (res) {
            wx.hideLoading()
            var tempFilePath = res.tempFilePath;
            _this.setData({
              imagePath: tempFilePath,
              zhuli:true
            });
          },
          fail(res) {
            wx.hideLoading()
            wx.showToast({
              title: res.errMsg,
              icon: 'none'
            })
          }
        })

      })
    },
    // 保存图片
    downImg(){
      let _this=this;
      authorize('writePhotosAlbum',(b)=>{
          if(b){
            wx.saveImageToPhotosAlbum({
              filePath: _this.data.imagePath,
              success() {
                wx.showToast({
                  title:'保存图片成功',
                  icon:'none'
                })
              }
            })
          }
      })
    },
    //隐藏图片
    hideImg(){
      this.setData({
        zhuli:false,
        imagePath:''
      })
    },
    //
    hideMask(){
      this.setData({
        share:false
      })
    }
  }
})